//
//  Authing.swift
//  guard
//
//  Created by linus on 2021/11/19.
//

import UIKit

public class Authing: NSObject {
    private static var _sAppId: String?
    public private(set) static var sAppId: String? {
        get { _sAppId }
        set { _sAppId = newValue }
    }
    
    private static var publicConfig: Config?
    private static var listeners: Array<Config.ConfigCallback> = Array<Config.ConfigCallback>()
    private static var isGettingConfig: Bool = false
    private override init() {}
    
    public static func initWithAppId(_ appId: String) {
        sAppId = appId
        requestPublicConfig()
    }
    
    public static func getPublicConfig(callback: @escaping Config.ConfigCallback) {
        if isGettingConfig {
            listeners.append(callback)
        }
        
        if let config = publicConfig {
            listeners.removeAll()
            callback(config)
        }
    }
    
    public static func requestPublicConfig() {
        guard let appId = sAppId, !appId.isEmpty else { return }
        isGettingConfig = true
        let url = "https://console.authing.cn/api/v2/applications/" + appId + "/public-config"
        Guardian.request(nil, url, "GET", nil) { (response) in
            if response.code == 200, let data = response.data {
                if let config = Config.parse(data: data) {
                    publicConfig = config
                }
            }
            fireCallBack(config: publicConfig)
        }
    }
    
    private static func fireCallBack(config: Config?) {
        OperationQueue.main.addOperation {
            for callback in listeners {
                callback(config)
            }
            listeners.removeAll()
            isGettingConfig = false
        }
    }
    
    public static func logout(callback o_callback: Callback<AnyObject?>?) {
        guard let callback = o_callback else {
            return
        }
        OperationQueue.init().addOperation {
            callback(true, nil)
        }
    }
}
